﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace GestorDeFlotasDesktop.RendirViajes
{
    public partial class RendierViajes : Form
    {
        public RendierViajes()
        {
            InitializeComponent();
            tb_importe.Enabled = false;
            using (SqlConnection con = Modelo.Modelo.createConnection())
            {
                SqlConnection con3 = Modelo.Modelo.createConnection();
                SqlDataAdapter da3 = new SqlDataAdapter("SELECT Id_Chofer, (Ch_Nombre + ', ' +Ch_Apellido) as Ch_Nombre FROM NUNCA_TAXI.Choferes WHERE Ch_Habilitado = 1", con3);
                DataSet ds3 = new DataSet();
                da3.Fill(ds3);
                cb_chofer.DataSource = ds3.Tables[0].DefaultView;
                cb_chofer.DisplayMember = "Ch_Nombre";
                cb_chofer.ValueMember = "Id_Chofer";
                cb_chofer.SelectedIndex = -1;
                Modelo.Modelo.closeConnection(con3);


                SqlConnection con2 = Modelo.Modelo.createConnection();
                SqlDataAdapter da2 = new SqlDataAdapter("SELECT * FROM NUNCA_TAXI.Turnos WHERE Tu_Habilitado = 1", con2);
                DataSet ds2 = new DataSet();
                da2.Fill(ds2);
                cb_turno.DataSource = ds2.Tables[0].DefaultView;
                cb_turno.DisplayMember = "Tu_Descripcion";
                cb_turno.ValueMember = "Id_Turno";
                cb_turno.SelectedIndex = -1;
                Modelo.Modelo.closeConnection(con2);
            }
        }

        private void calcular_Click(object sender, EventArgs e)
        {
            bool found = false;
            using (SqlConnection con_un = Modelo.Modelo.createConnection())
            {
                try
                {
                    Modelo.Modelo.openConnection(con_un);
                    SqlCommand comando_check_unique = new SqlCommand(Modelo.SqlQueries.getIsRelojEnabled(Convert.ToDateTime(tb_dia.Text + "/" + tb_mes.Text + "/" + tb_anio.Text), Convert.ToInt32(cb_chofer.SelectedValue), Convert.ToInt32(cb_turno.SelectedValue)), con_un);
                    SqlDataReader reader = comando_check_unique.ExecuteReader();
                    while (reader.Read())
                    {
                        if (!reader[0].ToString().Equals("1"))
                        {
                            found = true;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            if (!found)
            {

                if (cb_turno.SelectedValue != "" && cb_chofer.SelectedValue != "" && tb_dia.Text != "" && tb_anio.Text != "" && tb_mes.Text != "")
                {
                    string fecha = "'" + tb_anio.Text + "/" + tb_mes.Text + "/" + tb_dia.Text + "'";
                    using (SqlConnection con = Modelo.Modelo.createConnection())
                    {
                        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM NUNCA_TAXI.Viajes WHERE (Vi_FechaRendido IS NULL) AND (Id_Turno = " + cb_turno.SelectedValue + ") AND (Id_Chofer = " + cb_chofer.SelectedValue + ") AND (DATEADD(dd, 0, DATEDIFF(dd, 0, Vi_Fecha)) = " + fecha + ")", con);
                        DataTable dt = new DataTable();
                        da.Fill(dt);
                        dataGridView1.DataSource = dt;

                        da = new SqlDataAdapter("SELECT Id_Chofer, SUM(Vi_Importe) AS Monto_Rendicion FROM NUNCA_TAXI.Viajes WHERE (Vi_FechaRendido IS NULL) AND (Id_Turno = " + cb_turno.SelectedValue + ") AND (DATEADD(dd, 0, DATEDIFF(dd, 0, Vi_Fecha)) = " + fecha + ") AND (Id_Chofer = " + cb_chofer.SelectedValue + ") GROUP BY Id_Chofer", con);
                        dt = new DataTable();
                        da.Fill(dt);
                        if (dt.Rows.Count == 0)
                        {
                            MessageBox.Show("No hay elementos a mostrar");
                        }
                        else
                        {
                            tb_importe.Text = dt.Rows[0]["Monto_Rendicion"].ToString();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Por favor, complete todos los campos para continuar");
                }
            }
            else
            {
                MessageBox.Show("Reloj no esta habilitado");
            }
        }

        private void rendir_Click(object sender, EventArgs e)
        {
            bool found = false;
            using (SqlConnection con_un = Modelo.Modelo.createConnection())
            {
                try
                {
                    Modelo.Modelo.openConnection(con_un);
                    SqlCommand comando_check_unique = new SqlCommand(Modelo.SqlQueries.getIsRelojEnabled(Convert.ToDateTime(tb_dia.Text + "/" + tb_mes.Text + "/" + tb_anio.Text), Convert.ToInt32(cb_chofer.SelectedValue), Convert.ToInt32(cb_turno.SelectedValue)), con_un);
                    SqlDataReader reader = comando_check_unique.ExecuteReader();
                    while (reader.Read())
                    {
                        if (!reader[0].ToString().Equals("1"))
                        {
                            found = true;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            if (!found)
            {
                if (cb_turno.SelectedValue != "" && cb_chofer.SelectedValue != "" && tb_dia.Text != "" && tb_anio.Text != "" && tb_mes.Text != "")
                {
                    string fecha = "'" + tb_anio.Text + "/" + tb_mes.Text + "/" + tb_dia.Text + "'";
                    string fecha_aux = tb_anio.Text + "/" + tb_mes.Text + "/" + tb_dia.Text;
                    DateTime dt_fecha = DateTime.Parse(fecha_aux);
                    using (SqlConnection con = Modelo.Modelo.createConnection())
                    {
                        SqlCommand comando = new SqlCommand("UPDATE NUNCA_TAXI.Viajes SET Vi_FechaRendido=@fecha WHERE (Vi_FechaRendido IS NULL) AND (Id_Turno = " + cb_turno.SelectedValue + ") AND (Id_Chofer = " + cb_chofer.SelectedValue + ") AND (DATEADD(dd, 0, DATEDIFF(dd, 0, Vi_Fecha)) = " + fecha + ")", con);
                        comando.Parameters.AddWithValue("fecha", System.DateTime.Now);

                        try
                        {
                            Modelo.Modelo.openConnection(con);
                            comando.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        finally
                        {
                            Modelo.Modelo.closeConnection(con);
                        }

                        comando = new SqlCommand("INSERT INTO NUNCA_TAXI.Rendiciones(Id_Chofer,Id_Turno,Ren_Fecha,Ren_Importe) VALUES(@chofer,@turno,@fecha,@importe)", con);
                        comando.Parameters.AddWithValue("chofer", cb_chofer.SelectedValue);
                        comando.Parameters.AddWithValue("turno", cb_turno.SelectedValue);
                        comando.Parameters.AddWithValue("fecha", dt_fecha);
                        if (String.IsNullOrEmpty(tb_importe.Text))
                        {
                            comando.Parameters.AddWithValue("importe", 0);
                        }
                        else
                        {
                            comando.Parameters.AddWithValue("importe", Convert.ToDecimal(tb_importe.Text));
                        }
                        

                        try
                        {
                            Modelo.Modelo.openConnection(con);
                            comando.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        finally
                        {
                            Modelo.Modelo.closeConnection(con);
                            Login.Login.mainForm.openForm(new RendierViajes());
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Por favor, complete todos los campos para continuar");
                }
            }
            else
            {
                MessageBox.Show("Reloj no esta habilitado");
            }
        }
    }
}
